function [] = Keyboardupdate()
% This function draws the keyboard and the cursor depending on two variables
% Stationaryflag : Indicates if cursor is at rest
% Highlightedflag : Indicates if a key has been highlighted
% All variables are declared global so that they are updated in other
% functions

global hfig hax hrect hletter htext pt
global m n scrambled fontsize letters
global TYPEDTEXT
global stationaryflag movingflag highlightedflag outofbounds_flag NEWKEYPRESS OUTOFBOUNDSALLOWED
global xloc yloc
global TARGETS T targ_col targ_row
global T_IN_TARGET IN_OLD_TARGET CURR_TARG_HIT REFRESH_TARG TIME_AFTER_KEYPRESS TRANSITION_KEY
global CURSOR_DURING_TRIAL CURSOR_AFTER_TRIAL KEY_DURING_TRIAL KEY_AFTER_TRIAL TEXTFLAG SCOREFLAG
global CURR_KEY_ROW CURR_KEY_COL
global scorecard TOTSCORE TOTPOSSIBLESCORE SCORE_RECORD
global Topoutofbounds Leftoutofbounds Rightoutofbounds Botoutofbounds
global Topflag Leftflag Rightflag Botflag
global TARG_KEYS PUSH_KEYS
global cputime glovesignals mvt_start mvt_end T_IN_KEY T_OUT_KEY MT
global N_TARGETS
global insthandvel NUMFRAMES
global highlightrect
global bigloop IND_IN_KEY IND_OUT_KEY A_AMA 
global sqedge  goodsound badsound  SOUND_FLAG
global  A_mult TARGETS OFFSET OFFSETx OFFSETy OFFSETxy Key_feedback NO_FB_TRIAL

%Time to allow cursor to remain stationary before registering as a keypress
HOVER_TIME_THRESHOLD = 50;

%Time to switch between old and new target
TARGET_TRANSITION_TIME = 120;

%Four Cases Possible
%Key (highlighted/unhighlighted) x Cursor (Moving/Stationary)
% 1. Key - Unhighlighted, Cursor - Stationary: Highlight Key
% 2. Key - Highlighted, Cursor - Moving: Clear Highlight
% 3. Key - Highlighted, Cursor - Stationary: Update Target after a while
% 4. Key - Unhighlighted, Cursor - Moving: Do Nothing

%TRANSITION_KEY is a flag that is set when the target is about to be
%updated
%Once this flag has been set, the program runs until the new target is
%displayed regardless of the current state of the hand

if(stationaryflag == 1 && highlightedflag ==0 && TRANSITION_KEY==0) %Stationary with no highlight
    
    %Register the first time instand it entered key
    mvt_end = cputime;
    mvt_end_indx = bigloop;
    %Start timer to double check if they are truly stationary
    if(IN_OLD_TARGET == 0)
        T_IN_TARGET = T_IN_TARGET + 1;
    end
    
    %Update new Target if it has been inside target for sufficiently
    %long, else do nothing
    if(T_IN_TARGET > HOVER_TIME_THRESHOLD)
        
        %Find corresponding column and row pressed
        [col,row]=findcolrow(xloc,yloc,sqedge);
        
        %If valid key is pressed, highlight and display
        if(row>0 && row <=n && col >0 && col<=m)
            
            CURR_KEY_ROW = row; CURR_KEY_COL = col;
            %Check if the current key is the target key, If yes highlight in
            %yellow
            if (col == targ_col && row == targ_row)
                CURR_TARG_HIT = 1;
                if(KEY_AFTER_TRIAL ==1)
                    %Highlight key in yellow
                    [hax,hrect]=keyhighlight2(m,n,col,row,hrect,hax,hfig,fontsize,'y','k');
                    %play positive auditory response - hit the target
                    if (SOUND_FLAG == 1)
                        sound(goodsound,60000)
                    end
                end
            else
                %Highlight selected key in Black
                if(KEY_AFTER_TRIAL ==1)
                    [hax,hrect]=keyhighlight2(m,n,col,row,hrect,hax,hfig,fontsize,'k',[1 1 1]);

                    %play negative auditory response - missed the target
                    if (SOUND_FLAG == 1)
                        sound(badsound(1:2500),10000)
                    end

                end
            end
            
            %Find corresponding time this happened
            T_IN_KEY = [T_IN_KEY; mvt_end];
            IND_IN_KEY = [IND_IN_KEY; mvt_end_indx];
            
            
            MT = [MT; mvt_end-mvt_start];
            
            %Compute score (100 points for Hit, deduct 20 penalty points for each block away)
            penalty = 20; %100/max(m,n); %Compute penalty depending on size of grid
            err = max(abs(col-targ_col),abs(row-targ_row)); %Chessboard Distance
            
            score = 100- err*penalty;
            SCORE_RECORD = [SCORE_RECORD; score];
            TOTSCORE = TOTSCORE + score; %Running Total
            TOTPOSSIBLESCORE = TOTPOSSIBLESCORE + 100; %Maximum Possible score
            TYPEDTEXT = [TYPEDTEXT '  --  '];
            
            %Set the flag to indicate that they key has been highlighted
            highlightedflag = 1;
            
            
            %Set this Flag so that it does not keep repeating same
            %character
            IN_OLD_TARGET = 1;
            
            %Reset Time in Target
            T_IN_TARGET = 0;
            
            %Signal that a new key has been pressed (which is different
            %from saying the key is highlighted)
            NEWKEYPRESS = 1;
            
            %Set flag to update next target
            TRANSITION_KEY = 1;
            
            %Display Cursor On Top of Highlighted Key
            cursordisplay(CURSOR_AFTER_TRIAL)
            
        else
             %play negative auditory response - missed the target
              if (SOUND_FLAG == 1)
                   sound(badsound(1:2500),10000)
              end
              
            
            if(OUTOFBOUNDSALLOWED == 0)
                %Indicate that the key is out of range of keyboard
                outofbounds_flag = 1;
                T_IN_TARGET = 0;
            end
        end
    end
    
elseif(stationaryflag ==0 && highlightedflag ==1 && TRANSITION_KEY==0) %Starts to Move with Key Highlighted
    
    %Check if cursor is really moving
    if(movingflag==1)
        
        %Find Instant that the key starts to move
        mvt_start = cputime;
        T_OUT_KEY = [T_OUT_KEY; mvt_start];
        IND_OUT_KEY = [IND_OUT_KEY; bigloop];
        %Return back to default after highlighting
        [hax,hrect]=keyunhighlight2(m,n,CURR_KEY_COL,CURR_KEY_ROW,hrect,hax,hfig,fontsize,[1 1 1],'k');
        
        
        %Set flag that indicates highlighting is off
        highlightedflag = 0;
        
        %Refresh Target
        REFRESH_TARG = 1;
        
        
        
        %Reset the time counter that checks how long has elapsed since key
        %is stationary
        TIME_AFTER_KEYPRESS = 0;
        
        
        cursordisplay(CURSOR_AFTER_TRIAL)
        
    end
    
elseif((stationaryflag == 1 && highlightedflag == 1) || TRANSITION_KEY == 1) %Just sitting inside key after key has been highlighted
    
    if(NEWKEYPRESS == 1)
        
        TIME_AFTER_KEYPRESS = TIME_AFTER_KEYPRESS+1;
        
        if(CURR_TARG_HIT == 0)
            %Change Color of Old Target to Grey if it did not hit
            if(KEY_AFTER_TRIAL ==1)
                Targetkeyhighlight(m,n,targ_col,targ_row,hrect,hax,hfig,fontsize,[0.5 0.5 0.5]);

            end
        end
        
        TRANSITION_KEY = 1;%Set transition key - which means set new target no matter what the state
        
        if(TIME_AFTER_KEYPRESS>TARGET_TRANSITION_TIME)
            
            if(CURR_TARG_HIT == 0 || KEY_AFTER_TRIAL == 0) %If the current target was not hit (which means that key would be grey)
                %Make Old target "ungrey"
                Targetkeyhighlight(m,n,targ_col,targ_row,hrect,hax,hfig,fontsize,[1 1 1]);
            end
            
            
            %Update to new target
            T = T + 1; %Update new target
            REFRESH_TARG = 1;
            NEWKEYPRESS = 0;
            TRANSITION_KEY = 0;
            
        end
    end
    
    cursordisplay(CURSOR_AFTER_TRIAL);
    
    
else %Moving with No Key Highlighted
    
    %Clear flag that indicates that target was hit
    CURR_TARG_HIT = 0;
    
    %Moved out of highlighted key
    IN_OLD_TARGET = 0;
    
    TIME_AFTER_KEYPRESS = 0;
    
    [col,row]=findcolrow(xloc,yloc,sqedge);
    
    %Feedback of Key
    if(KEY_DURING_TRIAL==1)  %change to put in catch trials with no cursor feedback
       if (NO_FB_TRIAL==1)
           if (Key_feedback(T)==1) 
             keydisplay(col,row);
           end        
       else 
            keydisplay(col,row);
       end
    end
    
    %Cursor visibility when moving
    cursordisplay(CURSOR_DURING_TRIAL)
    
    %Clear out of bounds Box if it is set
    if(row>0 && row <=n && col >0 && col<=m)
        if(outofbounds_flag == 1)
            Drawoutofbounds(0,0,'r',1);
            outofbounds_flag = 0;
        end
    end
    
end
